/**
 * 
 */
package com.base.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.base.model.DemoCommand;
import com.base.model.LoginUser;
import com.base.model.MessageSend;

/**
 * @author ricky
 *
 */
public class MainObjectClient {

	public static String host = "127.0.0.1";
    public static int port = 7878;
    
    public static Long userId = 54321L;

    /**
     * @param args
     * @throws InterruptedException 
     * @throws IOException 
     */
    public static void main(String[] args) throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>(){
            	@Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    
                    pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(this
                            .getClass().getClassLoader())));
            		pipeline.addLast("encoder", new ObjectEncoder());
                    
                    // 客户端的逻辑
                    pipeline.addLast("handler", new ObjectClientHandler());
                }
            });

            // 连接服务端
            Channel ch = b.connect(host, port).sync().channel();
            
            DemoCommand loginCommand = getLoginCommand();
            ch.writeAndFlush(loginCommand);
            // 控制台输入
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (;;) {
                String line = in.readLine();
                if (line == null) {
                    continue;
                }
                /*
                 * 向服务端发送在控制台输入的文本 并用"\r\n"结尾
                 * 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。
                 * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码
                 * */
               // ch.writeAndFlush(line);
                
                DemoCommand messageCommand = getMessageCommand(line);
                ch.writeAndFlush(messageCommand);
            }
        } finally {
            // The connection is closed automatically on shutdown.
            group.shutdownGracefully();
        }
    }
    
    public static DemoCommand getLoginCommand(){
    	DemoCommand c = new DemoCommand();
    	c.setAction("login");
    	
    	LoginUser user = new LoginUser();
    	user.setId(userId);
    	user.setName(userId.toString());
    	
    	c.setBizObj(user);
    	c.setFromUserId(userId);
    	return c;
    }
    
    public static DemoCommand getMessageCommand(String message){
    	DemoCommand c = new DemoCommand();
    	c.setAction("sendMessage");
    	
    	MessageSend messageSend = new MessageSend();
    	messageSend.setMessage(message);
    	messageSend.setFromUserId(userId);
    	messageSend.setFromUserName(userId.toString());
    	messageSend.setSendToUserId(12345L);
    	
    	c.setBizObj(messageSend);
    	c.setFromUserId(userId);
    	return c;
    }
}
